package dataGoods

import (
	"context"
	goods_pb "mxshop/api/goods/v1"
	IGoods "mxshop/app/mxshop_api/api/internal/data/goods"
	"mxshop/app/mxshop_api/api/internal/domain/do/goods"
	"mxshop/gmicro/pkg/errors"
)

type brand struct {
	gc goods_pb.GoodsClient
}

func (b *brand) List(ctx context.Context, req *goods_pb.BrandFilterRequest) (*doGoods.BrandDOList, error) {
	var ret doGoods.BrandDOList

	rsp, err := b.gc.BrandList(ctx, req)
	if err != nil {
		return nil, errors.FromGrpcError(err)
	}

	for _, v := range rsp.Data {
		ret.Items = append(ret.Items, &doGoods.BrandDO{
			Id:   v.Id,
			Name: v.Name,
			Logo: v.Logo,
		})
	}
	ret.TotalCount = int64(rsp.Total)

	return &ret, nil
}

func (b *brand) Create(ctx context.Context, request *doGoods.BrandDO) error {
	protoBrand := &goods_pb.BrandRequest{
		Id:   request.Id,
		Name: request.Name,
		Logo: request.Logo,
	}
	rsp, err := b.gc.CreateBrand(ctx, protoBrand)
	if err != nil {
		return errors.FromGrpcError(err)
	}
	request.Id = rsp.Id
	return nil
}

func (b *brand) Update(ctx context.Context, request *doGoods.BrandDO) error {
	protoBrand := &goods_pb.BrandRequest{
		Id:   request.Id,
		Name: request.Name,
		Logo: request.Logo,
	}
	_, err := b.gc.UpdateBrand(ctx, protoBrand)
	if err != nil {
		return errors.FromGrpcError(err)
	}
	return nil
}

func (b *brand) Delete(ctx context.Context, id int64) error {
	_, err := b.gc.DeleteBrand(ctx, &goods_pb.BrandRequest{Id: id})
	if err != nil {
		return errors.FromGrpcError(err)
	}
	return nil
}

func newBrand(gc goods_pb.GoodsClient) IGoods.Brand {
	return &brand{
		gc: gc,
	}
}
